package com.qf.config;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.qf.pojo.resp.BaseResp;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 2021/11/16 0016
 * Time: 15:41
 * Description: No Description
 */
@Component
public class MyzuulFilter extends ZuulFilter {

    private final static List uriList=new ArrayList();
    //什么时候拦截
@Override
public String filterType() {
    return FilterConstants.PRE_TYPE;
}
//过滤器执行的顺序
@Override
public int filterOrder() {
    return FilterConstants.PRE_DECORATION_FILTER_ORDER;
}
//是否进行过滤
@Override
public boolean shouldFilter() {
     //判断哪些请求需要拦截，哪些请求放行
    RequestContext currentContext = RequestContext.getCurrentContext();
    HttpServletRequest request = currentContext.getRequest();
    String requestURI = request.getRequestURI();

    if (uriList.contains(requestURI)){
        return false;
    }
    return true;
}
//拦截请求需执行的方法
@Override
public Object run() throws ZuulException {
    RequestContext currentContext = RequestContext.getCurrentContext();
    HttpServletRequest request = currentContext.getRequest();

    HttpServletResponse response = currentContext.getResponse();
    //从request中获取token
    String token = request.getHeader("token");
    if (token==null){
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        BaseResp baseResp = new BaseResp(0,"用户未登录！",null,null);

        try {
            response.getWriter().write(JSON.toJSONString(baseResp));
        } catch (IOException e) {
            e.printStackTrace();
        }
        //将请求停止继续执行
        currentContext.setSendZuulResponse(false);
    }
    return null;
}

public MyzuulFilter(){
    //添加放行请求
    uriList.add("/qf-shop-user/user/getCode");

}
}
